//
//  MainPageViewController.m
//  LeftSlide
//
//  Created by huangzhenyu on 15/6/18.
//  Copyright (c) 2015年 eamon. All rights reserved.
//

#import "MainPageViewController.h"
#import "AppDelegate.h"

#import "WebViewController.h"
#import "MainCollectionViewCell.h"
#import "UIImageView+WebCache.h"
#import "MainTableViewCell.h"
#import "CaseViewController.h"
#import "AFRequdstAndLoad.h"
#import "MainData.h"
#import "CaseCollectionViewCell.h"



#define vBackBarButtonItemName  @"backArrow.png"    //导航条返回默认图片名
@interface MainPageViewController ()< UITableViewDataSource ,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,MBProgressHUDDelegate>{
    MBProgressHUD *HUD;
}

@property (nonatomic ,strong) UITableView * tableView;
@property (nonatomic ,strong) NSMutableDictionary *dic;
@property (nonatomic ,strong) NSMutableArray *arr;
@property (nonatomic ,strong) NSMutableArray *arr1;
@property (nonatomic ,strong) UICollectionView *collectionview;
@property (nonatomic ,strong) UICollectionView *collectionview1;
@property (nonatomic ,strong) NSMutableArray *array;
@property (nonatomic ,strong) UIView *view1;
@property (nonatomic ,assign) NSInteger num;
@property (nonatomic ,strong) UIPageControl *pageControl;
@property (nonatomic ,assign) NSTimer *timer;

@end

@implementation MainPageViewController
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)viewWillAppear:(BOOL)animated
{
    AppDelegate *appD = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appD.leftSlideVC setPanEnabled:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"首页";
//    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.num = 1;
    self.arr = [NSMutableArray array];
    self.dic = [NSMutableDictionary dictionary];
    self.arr1 = [NSMutableArray array];
    self.array = [NSMutableArray array];
    UIButton *menuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    menuBtn.frame = CGRectMake(0, 0, 20, 18);
    [menuBtn setBackgroundImage:[UIImage imageNamed:@"drawer.png"] forState:UIControlStateNormal];
    [menuBtn addTarget:self action:@selector(leftAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:menuBtn];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width , self.view.bounds.size.height) style:UITableViewStylePlain];
    self.tableView.separatorStyle = NO;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 310)];
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(10, 150, 200, 40);
    [self.tableView.tableHeaderView addSubview:label];
    label.textColor = [UIColor redColor];
    label.text = @"精品案例推荐";
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(120, 110);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionview = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 190,self.view.bounds.size.width, 110) collectionViewLayout:flowLayout];
    self.collectionview.delegate = self;
    self.collectionview.dataSource = self;
    self.collectionview.tag = 10000;
    self.collectionview.showsHorizontalScrollIndicator = NO;
    [self.tableView.tableHeaderView addSubview:self.collectionview];
    self.collectionview.backgroundColor = [UIColor clearColor];
    [self.collectionview registerClass:[MainCollectionViewCell class] forCellWithReuseIdentifier:@"hei"];
    [self.view addSubview:self.tableView];
    
    
    UICollectionViewFlowLayout *flowLayout1 = [[UICollectionViewFlowLayout alloc] init];
    flowLayout1.itemSize = CGSizeMake(ScreenWidth , 150);
    flowLayout1.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout1.minimumLineSpacing = 0;
    UICollectionView *collectionview = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0,ScreenWidth, 150)collectionViewLayout:flowLayout1];
    collectionview.backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,ScreenWidth, 150)];
    UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0,ScreenWidth, 150)];
    imageview.image = [UIImage imageNamed:@"baikejiaju.png"];
    [collectionview.backgroundView addSubview:imageview];
    

    
    collectionview.tag = 1000;
    collectionview.delegate = self;
    collectionview.dataSource = self;
    collectionview.pagingEnabled = YES;
    collectionview.showsHorizontalScrollIndicator = NO;
    [self.tableView.tableHeaderView addSubview:collectionview];
    [collectionview registerClass:[CaseCollectionViewCell class] forCellWithReuseIdentifier:@"hehe"];
    self.pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 110, ScreenWidth, 40)];
    self.pageControl.numberOfPages = 5;
    self.pageControl.pageIndicatorTintColor =  [UIColor colorWithRed:57/255.0 green:51/255.0 blue:49/255.0 alpha:1.0];
    [self.tableView.tableHeaderView addSubview:self.pageControl];
    //   self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(showtime:) userInfo:nil repeats:YES];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    self.tableView.footer = footer;
    if (![self.tableView.header isRefreshing]) {
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self handledata2];
        }];
        self.tableView.header = header;
    }
  

        
    [self handledata];
    [self handledata1];
    [self handledata2];
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.labelText = @"数据加载中...";
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(nightAction:) name:@"night" object:nil];
    
}

- (void)nightAction:(NSNotification *)sender
{
    self.view.backgroundColor = [sender.userInfo objectForKey:@"backcolor"];
    
    [_tableView reloadData];
    [_collectionview reloadData];
}

- (void)showtime:(NSTimer *)timer
{
    UICollectionView *collectionview = (UICollectionView *)[self.tableView.tableHeaderView viewWithTag:1000];
   
    if((NSInteger)collectionview.contentOffset.x % (NSInteger)ScreenWidth != 0){
        
        collectionview.contentOffset = CGPointMake(ScreenWidth, 0);
    }
    
    
    if ( collectionview.contentOffset.x < ScreenWidth*(self.array.count-1)) {
        [collectionview setContentOffset:CGPointMake(collectionview.contentOffset.x + ScreenWidth, 0) animated:YES];
    }
    else if ( collectionview.contentOffset.x == ScreenWidth *(self.array.count-1)){
        collectionview.contentOffset = CGPointMake(ScreenWidth, 0);
        [collectionview setContentOffset:CGPointMake( collectionview.contentOffset.x + ScreenWidth, 0) animated:YES];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    UICollectionView *collectionview = (UICollectionView *)[self.tableView.tableHeaderView viewWithTag:1000];
    if (scrollView.tag == 10000) {
    }else{
        self.pageControl.currentPage = (scrollView.contentOffset.x-ScreenWidth + 50)/ self.view.bounds.size.width;
    }
    if (collectionview.contentOffset.x >= ScreenWidth * (self.array.count - 1)) {
        collectionview.contentOffset = CGPointMake(ScreenWidth, 0);
    }else if((collectionview.contentOffset.x <= 0))
        collectionview.contentOffset = CGPointMake(ScreenWidth*(self.array.count-2), 0);
}


- (void)handledata
{
    NSString *str = @"http://www.meilele.com/mll_api/api/ad_common_api?ad_code=khapp_syjdt&city_id=75";
    [AFRequdstAndLoad dataURLStr:str datahand:^(id object) {
        self.dic = object;
        NSMutableArray *arr = [object objectForKey:@"khapp_syjdt"];
        //        if (object) {
        //             self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(showtime:) userInfo:nil repeats:YES];
        //        }
        for (NSMutableDictionary *dic1 in arr) {
            NSString *str1 = [NSString stringWithFormat:@"http://image.meilele.com/%@",[dic1 objectForKey:@"src"]];
            [self.array addObject:str1];
            [(UICollectionView *)[self.tableView.tableHeaderView viewWithTag:1000] reloadData];
        };
        UICollectionView *collectionview = (UICollectionView *)[self.tableView.tableHeaderView viewWithTag:1000];
        collectionview.contentOffset = CGPointMake(ScreenWidth, 0);
        NSString *str = self.array.lastObject;
        [self.array addObject:self.array.firstObject];
        [self.array insertObject:str atIndex:0];
        [self MBProgressHUD];
    }];
}
- (void)handledata1
{
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(globalQueue, ^{
        NSString *str1 = @"http://www.meilele.com/mll_api/api/app_ybj2_list?page=1&&size=49";
        [AFRequdstAndLoad dataURLStr:str1 datahand:^(id object) {
            self.arr = [[object objectForKey:@"ybjlist"] mutableCopy];
            [self MBProgressHUD];
            dispatch_async(mainQueue, ^{
                [_collectionview reloadData];
            });
        }];
    });
}

- (void)handledata2
{
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(globalQueue, ^{
        
        NSString *str = [NSString stringWithFormat:@"http://www.meilele.com/app?is_null=is_null&pageSize=20&startPage=%ld",(long)_num];
        //    NSString *str2 = @"http://www.meilele.com/app?is_null=is_null&pageSize=20&startPage=1";
        [AFRequdstAndLoad dataURLStr:str datahand:^(id object) {
            [self.arr1 removeAllObjects];
            NSArray *arr = [object objectForKey:@"rows"];
            for (NSMutableDictionary *dic in arr) {
                MainData *main = [[MainData alloc] init];
                [main setValuesForKeysWithDictionary:dic];
                [self.arr1 addObject:main];
            }
            [self.tableView.header endRefreshing];
                [self MBProgressHUD];
            dispatch_async(mainQueue, ^{
                
                [_tableView reloadData];
            });
        }];
    });
}



- (void)MBProgressHUD
{
    if (self.arr.count != 0 && self.arr1.count != 0 && self.array.count != 0 ) {
        [HUD hide:YES afterDelay:0];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(showtime:) userInfo:nil repeats:YES];
    }
}

- (void)loadMoreData
{
    ++_num;
    NSString *str = [NSString stringWithFormat:@"http://www.meilele.com/app?is_null=is_null&pageSize=20&startPage=%ld",(long)_num];
    [AFRequdstAndLoad dataURLStr:str datahand:^(id object) {
        if (object) {
            [self.tableView.footer endRefreshing];
            NSArray *arr = [object objectForKey:@"rows"];
            for (NSMutableDictionary *dic in arr) {
                MainData *main = [[MainData alloc] init];
                [main setValuesForKeysWithDictionary:dic];
                [self.arr1 addObject:main];
            }
        }
        [_tableView reloadData];
    }];
}

- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self.timer invalidate];
    
}
- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(showtime:) userInfo:nil repeats:YES];
    
    
}




- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView.tag == 1000) {
        
       
        return self.array.count;
        
        
    } else {
        
        return self.arr.count;
        
    }
    
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView.tag == 1000) {
        CaseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"hehe" forIndexPath:indexPath];
        NSString *str = [self.array objectAtIndex:indexPath.row];
        [cell.myimageview sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@"baikejiaju.png"]];
        
        return cell;
    }else{
        MainCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"hei" forIndexPath:indexPath];
        
        NSString *str = [[[[self.arr objectAtIndex:indexPath.row] objectForKey:@"suit"] objectAtIndex:0] objectForKey:@"img_600_400"];
        
        NSString *str1 = [[self.arr objectAtIndex:indexPath.row] objectForKey:@"house_name"];
        
        cell.mylabel.text = str1;
        [cell.myimageview sd_setImageWithURL:[NSURL URLWithString:str]placeholderImage:[UIImage imageNamed:@"baikejiaju.png"]];
        
        return cell;
    }
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView.tag == 1000) {
        
        
        WebViewController *web = [[WebViewController alloc] init];
        if (indexPath.row == 0) {
            
            NSString *str = [[[_dic objectForKey:@"khapp_syjdt"] objectAtIndex:4]  objectForKey:@"url"];
            
            web.str1 = str;
            
            [self.navigationController pushViewController:web animated:YES];
            
            
        }else if (indexPath.row == 6){
            
            
            NSString *str = [[[_dic objectForKey:@"khapp_syjdt"] objectAtIndex:1]  objectForKey:@"url"];
            
            web.str1 = str;
            
            [self.navigationController pushViewController:web animated:YES];
            
            
        }else{
            
            NSString *str = [[[_dic objectForKey:@"khapp_syjdt"] objectAtIndex:indexPath.row-1]  objectForKey:@"url"];
            
            web.str1 = str;
            
            [self.navigationController pushViewController:web animated:YES];
            
        }
        
        
    } else {
        
        CaseViewController *caseVC = [[CaseViewController alloc] init];
        
        caseVC.str = [[self.arr objectAtIndex:indexPath.row] objectForKey:@"suit_id"];
        NSString *str = [[[[self.arr objectAtIndex:indexPath.row] objectForKey:@"suit"] objectAtIndex:0] objectForKey:@"img_600_400"];
        caseVC.str1 = str;
        caseVC.titleCol = [[self.arr objectAtIndex:indexPath.row] objectForKey:@"house_name"];
        
        AppDelegate *appD = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [appD.leftSlideVC setPanEnabled:NO];
        
        [self.navigationController pushViewController:caseVC animated:YES];
    }
    
}






- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.arr1.count;
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"wode"];
    if (cell == nil) {
        cell = [[MainTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"wode"];
    }
    
    MainData *main = [self.arr1 objectAtIndex:indexPath.row];
    
    NSString *str = main.picture;
    
    NSString *str2 = [NSString stringWithFormat:@"http://image.meilele.com/%@",str];
    
    
    
    [cell.myimgageview1 sd_setImageWithURL:[NSURL URLWithString:str2] placeholderImage:[UIImage imageNamed:@"baikejiaju.png"]];
    NSString *str3 = main.goods_name;
    NSString *str4 = main.goods_price;
    NSString *str5 = [NSString stringWithFormat:@"￥ %@",str4];
    NSString *str6 = main.goods_total_sale;
    NSString *str7 = [NSString stringWithFormat:@"已售:%@",str6];
    cell.mylabel.text = str3;
    cell.mylabel1.text = str5;
    cell.mylabel2.text = str7;
    return cell;
}


- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MainData *main = [self.arr1 objectAtIndex:indexPath.row];
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSString *str = main.goods_url;
    NSString *str2 = [NSString stringWithFormat:@"http://m.meilele.com%@",str];
    
    WebViewController *web = [[WebViewController alloc] init];
    web.str1 = str2;
    [self presentViewController:web animated:YES completion:^{
        
    }];
//    [self.navigationController pushViewController:web animated:YES];
}


- (void)leftAction
{
    
    AppDelegate *appD = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (appD.leftSlideVC.closed) {
        [appD.leftSlideVC openLeftView];
    }else{
        [appD.leftSlideVC closeLeftView];
    }
    
}





//- (void) openOrCloseLeftList
//{
//    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//
//    if (tempAppDelegate.LeftSlideVC.closed)
//    {
//        [tempAppDelegate.LeftSlideVC openLeftView];
//    }
//    else
//    {
//        [tempAppDelegate.LeftSlideVC closeLeftView];
//
//    }
//}
//
//- (void)viewWillDisappear:(BOOL)animated
//{
//    [super viewWillDisappear:animated];
////    NSLog(@"viewWillDisappear");
//    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//    [tempAppDelegate.LeftSlideVC setPanEnabled:NO];
//}

//- (void)viewWillAppear:(BOOL)animated
//{
//    [super viewWillAppear:animated];
////    NSLog(@"viewWillAppear");
//    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//    [tempAppDelegate.LeftSlideVC setPanEnabled:YES];
//}

@end
